﻿namespace Sidvall.Data
{
	public class TransactionScopeFactory : Sidvall.Data.ITransactionScopeFactory
	{
		#region Business Members

		#region GetTransactionScope

		public Sidvall.Data.ITransactionScope GetTransactionScope()
		{
			TransactionSettings settings;

			settings = new TransactionSettings();

			return GetTransactionScope(settings);
		}

		public Sidvall.Data.ITransactionScope GetTransactionScope(TransactionSettings settings)
		{
			System.Transactions.TransactionScopeOption option;
			System.Transactions.IsolationLevel level;
			System.Transactions.TransactionScopeAsyncFlowOption asyncFlowOption;

			if (settings == null)
				settings = new TransactionSettings();
			switch (settings.ScopeOption)
			{
				case TransactionScopeOption.RequiresNew:
					option = System.Transactions.TransactionScopeOption.RequiresNew;
					break;
				case TransactionScopeOption.Suppress:
					option = System.Transactions.TransactionScopeOption.Suppress;
					break;
				default:
					option = System.Transactions.TransactionScopeOption.Required;
					break;
			}
			switch (settings.IsolationLevel)
			{
				case IsolationLevel.RepeatableRead:
					level = System.Transactions.IsolationLevel.RepeatableRead;
					break;
				case IsolationLevel.ReadCommitted:
					level = System.Transactions.IsolationLevel.ReadCommitted;
					break;
				case IsolationLevel.ReadUncommitted:
					level = System.Transactions.IsolationLevel.ReadUncommitted;
					break;
				case IsolationLevel.Snapshot:
					level = System.Transactions.IsolationLevel.Snapshot;
					break;
				case IsolationLevel.Chaos:
					level = System.Transactions.IsolationLevel.Chaos;
					break;
				case IsolationLevel.Unspecified:
					level = System.Transactions.IsolationLevel.Unspecified;
					break;
				default:
					level = System.Transactions.IsolationLevel.Serializable;
					break;
			}
			switch (settings.AsyncFlowOption)
			{
				case TransactionScopeAsyncFlowOption.Suppress:
					asyncFlowOption = System.Transactions.TransactionScopeAsyncFlowOption.Suppress;
					break;
				default:
					asyncFlowOption = System.Transactions.TransactionScopeAsyncFlowOption.Enabled;
					break;
			}
			return TransactionManager.GetTransactionScope(option, level, settings.Timeout, asyncFlowOption);
		}

		#endregion
		#region ToString

		public override string ToString()
		{
			return "TransactionScopeFactory - System.Transactions";
		}

		#endregion

		#endregion
	}
}
